<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;


use think\Db;
use think\Exception;
use Stbz\Api\SupplyClient;
class Task
{
    private $appKey   = 'A855F0BA1EBCD119BEFBDE6EC07ECE65';
    private $appSecret = '68B892679EB78F9FB45ED3D62DE838B7';
    /**
     * 7天信誉保证金释放
     */
    public function orderGive(){
        $ctm=time()-7*24*3600;//7天
        $where=[];
        $where['o.pay_status']=2;
        $where['o.order_status']=["in",[4,5]];
        $where['o.source_type']=["not in",[2,3]];
        $where['og.og_d_status']=3;
        $where['og.give_status']=1;
        $where['og.confirm _time']=['gt',$ctm];
        $orderGoods=Db::name("order_goods")
            ->alias("og")
            ->join("mm_order o","o.order_id=og.order_id")
            ->field("og.og_id,og.order_id")
            ->where($where)
            ->select();
        $tm=time();
        foreach ($orderGoods as $order){
            $orderID=$order['order_id'];
            $og_id=$order['og_id'];
            $logList=Db::name("member_asset_log")->where(['type'=>3,"relation_id"=>$orderID,'relation_sid'=>$og_id,'log_type_id'=>['in',[47,58]]])->select();
            Db::startTrans();
            try{
                if(!empty($logList)){

                        foreach ($logList as $log){
                            $mal_id=$log['mal_id'];
                            $logMember=$log['member_id'];
                            $amount=$log['amount'];
                            $change_type=$log['change_type'];
                            if($log['log_type_id']==47){
                                if( $change_type==1){
                                    $score_money= $amount;
                                    $coin_money= 0;
                                    $description="商城消费返利奖";
                                    $log_type_id="73";
                                }
                            }elseif($log['log_type_id']==58){
                                if( $change_type==1){
                                    $score_money= $amount;
                                    $coin_money= 0;
                                    $description="商城消费推荐奖";
                                    $log_type_id="5";
                                }elseif($change_type==2){
                                    $description="商城消费推荐奖";
                                    $log_type_id=72;
                                    $score_money= 0;
                                    $coin_money= $amount;
                                }
                            }

                            $asset_log[] = ['member_id' => $logMember, 'type' => 1, 'amount' =>  $amount,
                                'source_type' => 2, 'description' =>$description, "change_type" => $change_type, 'log_type_id' =>$log_type_id,
                                'relation_id' => $orderID,'relation_sid'=>$og_id, 'create_time' => $tm, 'update_time' => $tm,'release_status'=>2];

                            $num=Db::query("update mm_member_asset set frozen_score=frozen_score+$coin_money,seven_frozen_score=seven_frozen_score-$score_money,frozen_coin=frozen_coin+$coin_money,seven_frozen_coin=seven_frozen_coin-$coin_money where member_id=".$logMember." and seven_frozen_score>=".$score_money." and seven_frozen_coin>=".$coin_money);
                            if($num<=0){
                                throw new Exception("更新失败");
                            }
                        }
                        $num=Db::name("member_asset_log")->where(['type'=>3,"relation_id"=>$orderID,'relation_sid'=>$og_id,'log_type_id'=>[47,58]])->delete();
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                        $num=Db::name("member_asset_log")->insertAll($asset_log);
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                        $num=Db::name("order_goods")->where(['og_id'=>$og_id])->update(['give_status'=>4]);
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                }
                //更新订单状态
                $orderStatus=Db::name("order")->where(['order_id'=>$orderID])->value("status");
                $goodsList=Db::name("order_goods")->where(['order_id'=>$orderID])->field("og_d_status")->select();
                $isComplete=true;
                foreach ($goodsList as $ogoods){
                    if(!in_array($ogoods['og_d_status'],[3,4])||!in_array( $orderStatus,[4,5])){//未收货 未评价
                        $isComplete=false;
                    }
                }
                //订单交易完成
                if($isComplete){
                    $num=Db::name("order")->where(['order_id'=>  $orderID])->update(['status'=>12]);
                    if($num<=0){
                        throw new Exception("更新失败");
                    }
                }
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
            }

        }
    }

    /**
     * 释放积分
     */
    public function releaseScore(){

    }


    /**
     * 供应链提交订单
     */

    public function submitOrder(){
        $where=[];
        $where['is_order']=['neq',1];
        $where['status']=2;
        $where['pay_status']=2;
        $where['source_type']=['in',[2,3]];
        $orderList=Db::name('order')->where($where)->select();
        foreach ($orderList as $orderInfo){
            $orderSn=$orderInfo['order_sn'];

            $member_id=$orderInfo['member_id'];
            $orderGoods=Db::name("order_goods")->where(['order_id'=>$orderInfo['order_id']])->field("goods_id,spec_id,goods_num")->select();
            //供应链下单
            if(in_array($orderInfo['source_type'],[2,3])&&empty($orderInfo['is_order'])) {
                vendor("JuHe.autoload");
                $spuList=[];
                $ma_id=$orderInfo['ma_id'];
                $address=Db::name("member_address")->where(['ma_id'=>$ma_id,'member_id'=>$member_id])->find();
                $province = $address['province'];
                $city = $address['city'];
                $area = $address['county'];
                $street = empty($address['address_detail']) ? $address['county'] : $address['address_detail'];
                foreach ($orderGoods as $goods){
                    $spuList[]=[
                        'sku'=>$goods['spec_id'],
                        'number'=>$goods['goods_num'],
                    ];
                }
                $orderParam =[
                    'address'=>[
                        'consignee' => $address['m_name'],
                        'phone' => $address['m_mobile'],
                        'province' => $province,
                        'city' => $city,
                        'area' => $area,
                        'street' => $street,
                        'description' => $street,
                    ],
                    'spu'=>$spuList,
                    'orderSn'=>$orderSn
                ];
                Db::startTrans();
                try {
                    $num=Db::name("order")->where(['order_sn'=>$orderSn])->update(['is_order'=>1]);
                    if($num<=0){
                        throw new Exception("订单创建失败");
                    }

                    $orderParam['orderSn']=$orderSn;//商城订单号
                    $this->client = new SupplyClient( $this->appKey, $this->appSecret);
                    $response = $this->client->getApiResponse("POST","/v2/order", $orderParam);
                    $response =json_decode($response ,true);
                    if($response['code']!=1&&$response['code']!=3002){
                        throw new Exception("订单创建失败");
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                }
            }
        }

    }

}
//*/1 * * * * /usr/local/php/bin/php /iteam/mm-shop/think SupplyClientOrder >> /iteam/mm-shop/public/timelog/cron_`date +\%Y\%m\%d`.log 2>&1 &